package org.rpc.register;

import org.rpc.common.URL;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author tzf
 * @description: 远程注册中心
 * @date: 2023/11/17 16:06
 */

public class RemoteRegister {
    private static Map<String, List<URL>> REGISTER_MAP = new HashMap<>();
    private static final String defaultVersion = "1.0";
    private static final String FILE_NAME = "D:\\tempResource\\temp.txt";

    //注册服务
    public static void register(String interfaceName, URL url) {
        List<URL> urls = REGISTER_MAP.computeIfAbsent(url.getHostName(), k -> new java.util.ArrayList<>());
        urls.add(url);
        REGISTER_MAP.put(interfaceName, urls);
        saveFile();
    }

    public static List<URL> get(String interfaceName) {
        REGISTER_MAP = getMapFromFile();
        return REGISTER_MAP.get(interfaceName);
    }

    //保存文件
    public static void saveFile() {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(FILE_NAME);
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
            objectOutputStream.writeObject(REGISTER_MAP);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 获取map从文件
    public static Map<String, List<URL>> getMapFromFile() {
        try {
            FileInputStream fileInputStream = new FileInputStream(FILE_NAME);
            ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
            return (Map<String, List<URL>>) objectInputStream.readObject();
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}
